#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import time

import ruamel.yaml as yaml

from active.data import GetData, DataAnalysis
from active.recover import Recover
from dingTalk.dingTalkMessage import jdjc
from dingTalk.sendDingTalk import DingTalkAPI
from logger import logger


def main():
    hostlist = []
    logger.info("获取数据库信息")
    ys = yaml.load(open('./conf/dbinfo.yaml', 'r').read(), Loader=yaml.Loader)
    for db in ys['DBDIC_INFO']['mysql']:
        logger.info("获取集群数据")
        rs = GetData().get_from_mysql(db)
        logger.info("集群数据记录到influx")
        series = DataAnalysis().composite_data_for_influx(rs)
        DataAnalysis().set_influxdb(series)
        logger.info("检测数据")
        host = Recover().check(rs)
        if host:
            hostlist.append(host)
    for hosts in hostlist:
        logger.info("集群节点恢复")
        hostdb = Recover().recover(hosts)
        time.sleep(10)
        logger.info("重新检测节点状态")
        rs = GetData().get_from_mysql(hostdb)
        host = Recover().check(rs)
        if host is not None:
            msg = "{} 节点已恢复".format(hosts)
            logger.info(msg)
            # 钉钉通知
            nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
            dta = DingTalkAPI()
            dta.dingtalk(jdjc.format(msg, nowtime))
            logger.info("钉钉发送成功")


if __name__ == '__main__':
    main()
